package com.mly.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.mly.dao.UserDao;
import com.mly.entity.User;
import com.mly.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import orm.base.Ex.BaseServiceEx;
import orm.utils.BeanToMapUtil;
import wangchao.tools.CreateKey;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 示例Service
 *
 * @author 26061
 */
@Service
@Scope("prototype")
public class UserServiceImp extends BaseServiceEx implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public void init() {
        super.init(userDao);
    }

    @Override
    public JSONObject login(Map map, HttpSession session) throws Exception {
        if (map.get("userName") == null || "".equals(map.get("userName").toString()))
            return this.codeMess(eCode, "用户名不能为空");
        if (map.get("passWord") == null || "".equals(map.get("passWord").toString()))
            return this.codeMess(eCode, "密码不能为空");
        User user = userDao.selectp(map);
        if (user == null)
            return this.codeMess(eCode, "用户名或密码不正确");
        //生成token
        String token = CreateKey.getRandomString(16);

        //将新的token保存到数据库
        userDao.updatep(BeanToMapUtil.convertBean(user));
        JSONObject jsonObject = new JSONObject();
        session.setAttribute("user-" + token, user);
        jsonObject.put("token", token);
        jsonObject.put("msg", "登录成功");
        return this.codeData(jsonObject);
    }
}
